package com.nuoniu.sibanyun.service.crm.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nuoniu.sibanyun.entity.crm.CrmRetailLevel;
import com.nuoniu.sibanyun.entity.crm.CrmUserLevel;
import com.nuoniu.sibanyun.mapper.crm.CrmUserLevelMapper;
import com.nuoniu.sibanyun.service.crm.ICrmRetailLevelService;
import com.nuoniu.sibanyun.service.crm.ICrmUserLevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户等级 服务实现类
 * </p>
 *
 * @author 小啊刚
 * @since 2022-05-25
 */
@Service
public class CrmUserLevelServiceImpl extends ServiceImpl<CrmUserLevelMapper, CrmUserLevel> implements ICrmUserLevelService {

    @Autowired
    private ICrmRetailLevelService levelService;

    @Override
    public CrmUserLevel getByUserId(Integer shareUserId, Integer year, Integer month) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("user_id", shareUserId);
        wrapper.eq("year", year);
        wrapper.eq("month", month);
        wrapper.last("LIMIT 1");
        return getOne(wrapper);
    }


    @Override
    public void saveLevel(CrmUserLevel userLevel) {
        List<CrmRetailLevel> levelList = levelService.getList();
        for(CrmRetailLevel level : levelList) {
            if(level.getMode().equals(1)) {
                if(userLevel.getCrmCount() >= level.getCrmCount() || userLevel.getOrderCount() >= level.getCrmCount() || userLevel.getInviteCount() >= level.getInviteCount()
                        || userLevel.getOrderAmount().compareTo(level.getOrderAmount()) == 1 || userLevel.getSettlementCommission().compareTo(level.getSettlementCommission()) == 1) {
                    userLevel.setLevel(level.getLevel());
                    userLevel.setName(level.getName());
                    userLevel.setDirectCommission(level.getDirectCommission());
                    break;
                }
            } else {
                if(userLevel.getCrmCount() >= level.getCrmCount() && userLevel.getOrderCount() >= level.getCrmCount() && userLevel.getInviteCount() >= level.getInviteCount()
                        && userLevel.getOrderAmount().compareTo(level.getOrderAmount()) == 1 && userLevel.getSettlementCommission().compareTo(level.getSettlementCommission()) == 1) {
                    userLevel.setLevel(level.getLevel());
                    userLevel.setName(level.getName());
                    userLevel.setDirectCommission(level.getDirectCommission());
                    break;
                }
            }
        }

        this.saveOrUpdate(userLevel);
    }
}
